<?php

namespace app\enterprise\controller;

use app\enterprise\model\course\Exam as ExamModel;
use app\enterprise\model\course\ExamLinkTopic;
use app\enterprise\model\course\Topic;
use app\enterprise\model\course\ExamLinkTopic as ExamLinkTopicModel;
use app\enterprise\model\TrainType as TrainTypeModel;
use app\enterprise\service\DataType;
use think\exception\ValidateException;
use think\Request;

class Exam extends Enterprise
{
    public function list(Request $request)
    {
        $page= input('page', 1);
        $limit = input('size', 10);
        $exam_name = input('exam_name', '');
        $ids = input('ids', '');
        $exclude_ids = input('exclude_ids', '');
        $create_type = input('create_type', '');
        $typeIds = input('type_ids', []);

        $userIds = userIds($this->adminId);
        $where = [];

//        $where[] = ['creator_id', 'in', $userIds];
        $where[] = [ 'status','=',1];

        // 公共资源
        $resource_type = input('resource_type', '');
        if ( !empty($resource_type) ) {
            // 我的资源, 包含公共的, 平台的, 我的
            if ( $resource_type == 1 || $resource_type == 2 ) {
                $where[] = [ 'resource_type','=', $resource_type ];
            } else if ( $resource_type == 3 ) {
                // 只查我的
                $where[] = ['creator_id', '=', $userIds];
                $where[] = [ 'resource_type','=', $resource_type ];
                // 我的资源, 包含公共的, 平台的, 我的
//                $where[] = [ 'resource_type','in', '1,2,3' ];
            }
        }

        $data = ExamModel::order('id', 'desc')
            ->when($ids, function ($query) use ($ids) {
                $query->whereIn('id', $ids);
            })
            ->when(!empty($title), function ($query) use ($exam_name) {
                $query->where('exam_name', 'like', '%' . $exam_name . '%');
            })
            ->when(!empty($typeIds), function ($query) use ($typeIds) {
                foreach ($typeIds as $typeId) {
                    $query->whereOr('type_ids', 'like', '%,' . $typeId . ',%');
                }
            })
//            ->where(function ($query) use ($create_type) {
//                if (empty($create_type)) {
//                    $query->where('company_id', $this->adminId)->whereOr('company_id', 0);
//                } else if ($create_type == 1) {
//                    $query->where('company_id', 0);
//                } else {
//                    $query->where('company_id', $this->adminId);
//                }
//            })
            ->where($where)
            ->paginate($limit)
            ->each(function ($item) {
                if ($item['type_ids']) {
                    $typeIds = explode(',', $item['type_ids'] ?? '');
                    $types = TrainTypeModel::whereIn('id', $typeIds)
                        ->column('title');
                    $item->type_name = implode(',', $types);
                }
            });

//        $list = $data->items();
//        $del_total_num = 0;
//        // 如果是 我的资源, 需要筛选出来 自己的
//        if ( $resource_type == 3 ) {
//            foreach ($list as $key => &$value) {
//                if ( $value['resource_type'] == 3 && $value['creator_id'] != $this->adminId ) {
//                    unset($list[$key]);
//                    $del_total_num += 1;
//                }
//            }
//        }
        return app('json')->success([
            'list' => $data->items(),
            'total' => $data->total(),
            'total_page'=>$data->lastPage(),
        ]);
    }

    public function info()
    {
        $id = input('id', '');
        if ($id) {
            $data = ExamModel::getOne($id);
            try {
                $trainTypeRelates = DataType::getTrainTypeRelates($data['type_ids']);
                $data['selected_type_ids'] = $trainTypeRelates['id_chains'];

                $data['type_names'] =  '-';
                if (!empty($trainTypeRelates['title_chains'])) {
                    $data['type_names'] = implode('/', array_map(function ($item) {
                        return implode('-', $item);
                    }, $trainTypeRelates['title_chains']));
                }

                $data['type_ids'] = explode(',', trim($data['type_ids'], ','));


            } catch (\Exception $e) {
                $data['type_ids'] = [];
            }
            $topic_ids = ExamLinkTopicModel::where('exam_id', '=', $id)->column('topic_id');
            $data['topic_ids'] = $topic_ids;
        } else {
            $data = null;
        }
        $types = DataType::getTrainType();

        return app('json')->success([
            'data' => $data,
            'types' => $types,
        ]);
    }

    public function save(Request $request)
    {
        $data = $request->only([
            'type_ids', 'exam_name', 'min_point', 'more_num', 'dan_num', 'dan_point', 'duo_num', 'duo_point',
            'pan_point', 'pan_num', 'exam_limit_time'
        ]);

        try {
            validate([
                'type_ids|培训类型' => 'require|array',
                'exam_name|试卷名称'=> 'require|max:255',
                'min_point|合格分数'=> 'require|number|max:100',
                'more_num|不合格补考次数'=> 'require|integer',
                'dan_num|单选题数量'=> 'require|number',
                'dan_point|单选题分数'=> 'require|number',
                'duo_num|多选题数量'=> 'require|number',
                'dan_point|多选题分数'=> 'require|number',
                'pan_point|判断题分数'=> 'require|number',
                'pan_num|判断题数量'=> 'require|number',
                'exam_limit_time|考试时间'=> 'number',
            ])->check($data);
        } catch (ValidateException $e) {
            return app('json')->fail($e->getError());
        }

        // 校验所有题型总分不能超过100
        $total_point = $data['dan_point'] * $data['dan_num'] + $data['duo_point'] * $data['duo_num'] + $data['pan_point'] * $data['pan_num'];
        if ($total_point != 100) {
            return app('json')->fail('所有题型总分必须为100');
        }

        $id = input('id', '');
        $data['type_ids'] = ','.implode(',', $data['type_ids']).',';



        if (!$id) {
            $create_type = input('create_type', 2);
            $data['company_id'] = $this->adminId;
            // 是否是公共资源
            $resource_type = input('resource_type', '');
            if ( !empty($resource_type)  )  {
                $data['resource_type'] = $resource_type;
            }
            $data['creator_id'] = $this->adminId;
            $res = ExamModel::create($data);
            $id = $res->id;

//            if (!empty($topic_ids)) {
//                $topicData = [];
//                $length = count($topic_ids);
//                foreach ($topic_ids as $topic_id) {
//                    $topicData[] = [
//                        'exam_id' => $id,
//                        'topic_id' => $topic_id,
//                        'sort'=>$length
//                    ];
//                    $length--;
//                }
//                (new ExamLinkTopic())->saveAll($topicData);
//            }
        } else {
            $exam = ExamModel::getOne($id);
            if (!$exam) {
                return app('json')->fail('要操作的数据不存在');
            }
//            if ($exam['company_id'] != $this->adminId) {
//                return app('json')->fail('您没有权限操作该数据');
//            }
            $res = ExamModel::update($data, ['id' => $id]);
        }

        return app('json')->success();
    }

    public function addTopic()
    {
        $id = input('id', '');

        $topic_ids = input('topic_ids', []);

        if (empty($id)) {
            return app('json')->fail('请选择要操作的数据');
        }

        if (empty($topic_ids)) {
            return app('json')->fail('请选择要添加的试题');
        }

        $exam = ExamModel::getOne($id);

        if (!$exam) {
            return app('json')->fail('要操作的数据不存在');
        }

        if ($exam['company_id'] != $this->adminId) {
            return app('json')->fail('您没有权限操作该数据');
        }

        $last = ExamLinkTopic::where('exam_id', $id)
            ->max('sort');

        $topicData = [];

        $existTopicIds = ExamLinkTopic::where('exam_id', $id)->column('topic_id');

        foreach ($topic_ids as $topic_id) {
            if (in_array($topic_id, $existTopicIds)) {
                continue;
            }
            $topicData[] = [
                'exam_id' => $id,
                'topic_id' => $topic_id,
                'sort'=>$last+1
            ];
            $last = $last+1;
        }
        (new ExamLinkTopic())->saveAll($topicData);
        return app('json')->success();
    }

    public function saveTopic()
    {
        $id = input('id', '');



        $dan_wareids = input('dan_wareids', []);
        $pan_wareids = input('pan_wareids', []);
        $duo_wareids = input('duo_wareids', []);

        if (empty($id)) {
            return app('json')->fail('请选择要操作的数据');
        }

        $exam = ExamModel::getOne($id);

        if (!$exam) {
            return app('json')->fail('要操作的数据不存在');
        }

        if ($exam['company_id'] != $this->adminId) {
            return app('json')->fail('您没有权限操作该数据');
        }


        $dan_wareids = array_unique($dan_wareids);
        $pan_wareids = array_unique($pan_wareids);
        $duo_wareids = array_unique($duo_wareids);

        if ($exam['dan_num'] != count($dan_wareids)) {
            return app('json')->fail('单选题数量与试卷设置不一致');
        }

        if ($exam['duo_num'] != count($duo_wareids)) {
            return app('json')->fail('多选题数量与试卷设置不一致');
        }

        if ($exam['pan_num'] != count($pan_wareids)) {
            return app('json')->fail('判断题数量与试卷设置不一致');
        }


        $data = [
            'dan_wareids' => implode(',', $dan_wareids),
            'pan_wareids' => implode(',', $pan_wareids),
            'duo_wareids' => implode(',', $duo_wareids),
        ];
        ExamModel::update($data, ['id' => $id]);

        ExamLinkTopicModel::where('exam_id', $id)->delete();

        $topicData = [];
        $last = 0;
        if (!empty($dan_wareids)) {
            foreach ($dan_wareids as $topic_id) {
                $topicData[] = [
                    'exam_id' => $id,
                    'topic_id' => $topic_id,
                    'sort'=>$last+1
                ];
                $last = $last+1;
            }
        }
        if (!empty($duo_wareids)) {
            foreach ($duo_wareids as $topic_id) {
                $topicData[] = [
                    'exam_id' => $id,
                    'topic_id' => $topic_id,
                    'sort'=>$last+1
                ];
                $last = $last+1;
            }
        }
        if (!empty($pan_wareids)) {
            foreach ($pan_wareids as $topic_id) {
                $topicData[] = [
                    'exam_id' => $id,
                    'topic_id' => $topic_id,
                    'sort'=>$last+1
                ];
                $last = $last+1;
            }
        }
        (new ExamLinkTopic())->saveAll($topicData);


        return app('json')->success();
    }

    public function delete(Request $request)
    {
        $id = input('id', '');
        $data = ExamModel::getOne($id);
        if (!$id || !$data) {
            return app('json')->fail('要操作的数据不存在');
        }
        if ($data['company_id'] != $this->adminId) {
            return app('json')->fail('您没有权限操作该数据');
        }

        //
//        $exists = StaffExam::where('exam_id', $id)
//            ->where('status', 1)
//            ->count();
//        if ($exists) {
//            return app('json')->fail('当前试卷已使用，不可删除');
//        }
        ExamModel::dataDelete($id);
        ExamLinkTopic::where(['exam_id' => $id])->delete();
        return app('json')->success();
    }

    public function topics()
    {
        $exam_id = input('exam_id', 0);
        $limit = input('size', 10);
        $page = input('page', 1);
        $topic_title = input('topic_title', '');
        $topic_type = input('topic_type', 1);

        if (!$exam_id) {
            return app('json')->success([
                'list' => [],
            ]);
        }

        $exam = ExamModel::getOne($exam_id);

        if (empty($exam)) {
            return app('json')->success([
                'list' => [],
            ]);
        }
        $topic_ids = '';
        if ($topic_type == 1) {
            $topic_ids = $exam['dan_wareids'];
        } else if ($topic_type == 2) {
            $topic_ids = $exam['duo_wareids'];
        } else if ($topic_type == 3) {
            $topic_ids = $exam['pan_wareids'];
        } else {
            return app('json')->success([
                'list' => [],
            ]);
        }
        if (empty($topic_ids)) {
            return app('json')->success([
                'list' => [],
            ]);
        }

        $topic_ids = explode(',', $topic_ids);
        $topics = Topic::whereIn('id', $topic_ids)->where('status', 1)->orderField('id', $topic_ids)->select()->toArray();




//        $query = ExamLinkTopic::hasWhere('topic', function ($q) use ($topic_title, $topic_type) {
//            $q->where('status', 1);
//            if ($topic_title) {
//                $q->where('title', 'like', '%' . $topic_title . '%');
//            }
//            if ($topic_type) {
//                $q->where('type', $topic_type);
//            }
//        });
//
//        $data = $query->where('exam_id', $exam_id)->order('sort desc, topic_id asc')->paginate($limit);
//        $items = $data->items();

//        $topics = [];
//
//        foreach ($items as $item) {
//            $topic = $item->topic;
//            $topic['topic_id'] = $topic['id'];
//            $topic['sort'] = $item['sort'];
//            $topics [] = $topic;
//        }

        return app('json')->success([
            'list' => $topics,
//            'total' => $data->total(),
//            'total_page'=>$data->lastPage(),
        ]);
    }

    public function deleteTopic()
    {

        $exam_id = input('exam_id', 0);
        $topic_id = input('topic_id', 0);

        if (!$exam_id || !$topic_id) {
            return app('json')->fail('要操作的数据不存在');
        }

        $exam = ExamModel::getOne($exam_id);

        if (!$exam) {
            return app('json')->fail('要操作的数据不存在');
        }

        if ($exam['company_id'] != $this->adminId) {
            return app('json')->fail('您没有权限操作该数据');
        }

        ExamLinkTopic::where(['exam_id' => $exam_id, 'topic_id' => $topic_id])->delete();

        return app('json')->success();

    }

    public function switchSort()
    {
        $param = $this->request->param();
        $exam_id = input('exam_id', 0);
        $topic_id = input('topic_id', 0);
        $type = input('type', ''); // up / down
        $topic_title = input('topic_title', '');
        $topic_type = input('topic_type', '');

        try {
            validate([
                'exam_id|试卷id' => 'require|number',
                'topic_id|试题id' => 'require|number',
                'type|操作方式' => 'require|in:up,down'
            ])->check($param);
        } catch (ValidateException $exception) {
            return app('json')->fail($exception->getMessage());
        }

        $exam = ExamModel::getOne($exam_id);
        if (!$exam) {
            return app('json')->fail('要操作的数据不存在');
        }
        if ($exam['company_id'] != $this->adminId) {
            return app('json')->fail('您没有权限操作该数据');
        }

        // 查询当前题目的排序值
        $current = ExamLinkTopic::where([
            ['exam_id', '=', $exam_id],
            ['topic_id', '=', $topic_id]
        ])->find();
        if (!$current) {
            return app('json')->fail('题目不存在');
        }
        // 构建查询条件
        $query = ExamLinkTopic::where('exam_id', $exam_id);


        $query = ExamLinkTopic::hasWhere('topic', function ($q) use ($topic_title, $topic_type) {
            $q->where('status', 1);
            if ($topic_title) {
                $q->where('title', 'like', '%' . $topic_title . '%');
            }
            if ($topic_type) {
                $q->where('type', $topic_type);
            }
        })
            ->where('exam_id', $exam_id);

        if ($type === 'up') {

            // 找到比当前 sort 大但最小的那个
            $neighbor = $query->where('sort', '>', $current['sort'])
                ->order('sort desc, topic_id asc')
                ->find();

        } else {
            // 找到比当前 sort 小但最大的那个
            $neighbor = $query->where('sort', '<', $current['sort'])
                ->order('sort desc, topic_id asc')
                ->find();
        }

        if (!$neighbor) {
            return app('json')->fail('无法移动，已在边界');
        }

        // 交换 sort 值
        ExamLinkTopic::where('exam_id', $exam_id)->where('topic_id', $topic_id)->update(['sort' => $neighbor['sort']]);
        ExamLinkTopic::where('exam_id', $exam_id)->where('topic_id', $neighbor['topic_id'])->update(['sort' => $current['sort']]);
        return app('json')->success('移动成功');
    }
}